package com.udream.support.kuaidi100;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import com.google.common.reflect.TypeToken;
import com.udream.common.StringUtil;
import com.udream.support.GsonUtil;

/**
 * 快递公司工具类
 * 
 * @author zhaidong
 *
 */
public class KuaidiUtil {

 public List<KuaiDiEntity> getKuaiDiEntities() {

		return null;
	}

	/**
	 * 获取快递公司列表信息
	 * 
	 * @return
	 */
	@SuppressWarnings("serial")
 public static List<KuaiDiEntity> getCompanyList() {
		String jsonString = readToString();
  List<KuaiDiEntity> kdList = GsonUtil.getGson().fromJson(jsonString, new TypeToken<List<KuaiDiEntity>>() {
		}.getType());
		return kdList;
	}

	/**
	 * JSON数据装入内存
	 * 
	 * @return
	 */
	public static String readToString() {
		String encoding = "UTF-8";
		File file = new File(KuaidiUtil.class.getResource("company.json").getPath());
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 根据拼音获取具体的快递公式名称
	 * 
	 * @param pinyin
	 * @return
	 */
	public static String getCompanyName(String pinyin) {
		String name = "";
		if (StringUtil.isEmpty(pinyin)) {
			return name;
		}
  List<KuaiDiEntity> kdList = getCompanyList();
  for (KuaiDiEntity entity : kdList) {
			if (pinyin.trim().equals(entity.getCode())) {
				name = entity.getCompanyname();
				break;
			}
		}
		return name;
	}

	public static void main(String[] args) {
		System.out.println(KuaidiUtil.getCompanyName("yuantong"));
	}
}
